package com.ruyuan.seckill.service.impl;

import com.ruyuan.seckill.domain.dto.OrderDTO;
import com.ruyuan.seckill.domain.enums.QuantityType;
import com.ruyuan.seckill.domain.vo.CartSkuVO;
import com.ruyuan.seckill.domain.vo.GoodsQuantityVO;
import com.ruyuan.seckill.domain.vo.TradeVO;
import com.ruyuan.seckill.service.GoodsQuantityClient;
import com.ruyuan.seckill.service.GoodsStockLockManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 *  订单库存管理组件实现类
 */
@Service
@Slf4j
public class GoodsStockLockManagerImpl implements GoodsStockLockManager {
    @Autowired
    private GoodsQuantityClient goodsQuantityClient;

    /**
     * 秒杀扣除redis库存
     *
     * @param tradeVO 交易对象信息
     */
    @Override
    public boolean onSeckillRedisStockDeduction(TradeVO tradeVO) {
        if (tradeVO == null) {
            throw new NullPointerException("交易不存在");
        }
        //获取交易中的订单集合
        List<OrderDTO> orderDTOS = tradeVO.getOrderList();
        boolean orderStatus = true;

        for (OrderDTO order : orderDTOS) {
            boolean bool = seckillRedisStockDeduction(order);
            if (!bool) {
                return false;
            }
        }
        return true;
    }

    /**
     * 扣减秒杀库存
     *
     * @param orderDTO 订单
     * @return
     */
    private boolean seckillRedisStockDeduction(OrderDTO orderDTO) {
        return lockSeckillStock(orderDTO);
    }

    /**
     * 锁秒杀商品库存
     *
     * @param order
     * @return
     */
    private boolean lockSeckillStock(OrderDTO order) {

        // 获取订单中的sku信息
        List<CartSkuVO> skuList = order.getSkuList();
        // 根据购物车列表构建要扣减的库存列表
        List<GoodsQuantityVO> goodsQuantityVOList = buildQuantityList(skuList);

        // 扣减正常库存，注意：如果不成功，库存在脚本里已经回滚，程序不需要回滚
        boolean normalResult = goodsQuantityClient.updateSeckillSkuQuantity(goodsQuantityVOList);

        log.info("订单【" + order.getSn() + "】商品锁库存结果为：" + normalResult);
        return normalResult;
    }

    /**
     * 根据购物车列表构建要扣减的库存列表
     *
     * @param skuList
     * @return
     */
    private List<GoodsQuantityVO> buildQuantityList(List<CartSkuVO> skuList) {

        List<GoodsQuantityVO> goodsQuantityVOList = new ArrayList<>();
        for (CartSkuVO sku : skuList) {
            log.debug("cart num is " + sku.getPurchaseNum());
            GoodsQuantityVO goodsQuantity = new GoodsQuantityVO();
            goodsQuantity.setSkuId(sku.getSkuId());
            goodsQuantity.setGoodsId(sku.getGoodsId());

            //设置为负数，要减掉的
            goodsQuantity.setQuantity(-sku.getNum());

            //设置为要扣减可用库存
            goodsQuantity.setQuantityType(QuantityType.enable);
            goodsQuantityVOList.add(goodsQuantity);

        }

        return goodsQuantityVOList;
    }
}
